var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const fs = require('fs');
var logger = require('morgan');
const rp = require('request-promise');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const colors = require('colors');
global.config = require('./config.js');
const redis = require('./redis');

var app = express();
global.staticPath = path.join(__dirname, 'public')
app.use(logger('dev'));

function getClientIp (req) {
  return (req.headers['x-forwarded-for'] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.connection.socket.remoteAddress || '').replace(/:|f/g, '');
}
// 到 https://lbs.amap.com/api/webservice/guide/api/ipconfig 高德平台申请，每天最高5千次调用
const getIpLocatePlatformKey = '9770a49beb6b311fc1a6bd474764fe28';
async function getIpAndCity(req, res, next){
  const ip = getClientIp(req);

  if (['127', '10', '192', '1'].includes(ip.split('.')[0]) || req.url.includes('thumbnails') || req.url.includes('.js') || req.url.includes('.css')) {
    console.log(colors.blue(`Ip: ${ip}`))
    next();
    return;
  }
  // 根据请求 ip，获取 ip 的省市
  const city = await rp({
    method: 'GET',
    uri: `https://restapi.amap.com/v3/ip?key=${getIpLocatePlatformKey}&ip=${ip}`,
    json: true,
    timeout: 5000,
  });
  console.log(colors.bgBlue(`Ip: ${ip} 所属省：${city.province}  ${city.city}`));
  next()
}

app.use(getIpAndCity);

let deletetHtml = false
let deletetFolder = false
let deletetJquery = false
app.all("*",function(req,res,next){
	console.log('pid：', process.pid)
	next();
});
app.all("*",function(req,res,next){
	res.header("Access-Control-Allow-Origin","*");
	res.header("Access-Control-Allow-Headers","X-Requested-With,content-type,Autherization");
	res.header("Access-Control-Allow-Methods","POST,GET");
  res.header("Access-Control-Allow-Credentials", "true");
	next();
});
// 是否存在index.html，不存在则写入
if (!fs.existsSync(`${staticPath}/index.html`)) {
  fs.writeFileSync(`${staticPath}/index.html`, fs.readFileSync('./public/index.html'))
  deletetHtml = true
}
// 是否存在javascripts文件夹，不存在则创建，并写入jquery
if (!fs.existsSync(`${staticPath}/javascripts`)) {
  fs.mkdirSync(`${staticPath}/javascripts`);
  fs.writeFileSync(`${staticPath}/javascripts/jquery.min.js`, fs.readFileSync('./public/javascripts/jquery.min.js'))
  deletetFolder = true
  deletetJquery = true
}
// 也可能该目录本身就有javascripts文件夹及其它一些文件，但是没有jquery
if(!fs.existsSync(`${staticPath}/javascripts/jquery.min.js`)){
  fs.writeFileSync(`${staticPath}/javascripts/jquery.min.js`, fs.readFileSync('./public/javascripts/jquery.min.js'))
  deletetJquery = true
}

// view engine setup
app.set('views', path.join(__dirname, 'views'));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.set('view engine', 'jade');
app.use(express.static(staticPath));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

process.on('SIGINT', function () {
  if (staticPath != './public' && deletetHtml) fs.unlinkSync(`${staticPath}/index.htm`)
  if (staticPath != './public' && deletetJquery) fs.unlinkSync(`${staticPath}/javascripts/jquery.min.js`)
  if (staticPath != './public' && deletetFolder) fs.rmdirSync(`${staticPath}/javascripts`)
  process.exit(0);
});

module.exports = app;
